package com.hotel.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hotel.component.BaseController;
import com.hotel.component.IocContainer;
import com.hotel.entity.Option;
import com.hotel.entity.PageBean;
import com.hotel.entity.User;
import com.hotel.exception.EntityException;
import com.hotel.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author Str
 * @Date 2021/10/26 19:15
 * @Description :用户管理
 */
@WebServlet("/user/*")
public class UserController extends BaseController {
    private UserService userService = (UserService) IocContainer.getBean("UserService");

    // 跳转到首页
    public String index(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        return "forward:/jsp/index.jsp";
    }

    // 跳转到用户列表
    public String viewList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        return "forward:/jsp/user/list.jsp";
    }

    // 跳转到新增用户页面
    public String viewAddUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        return "forward:/jsp/user/addUser.jsp";
    }

    // 获取昵称和id
    public String getNickNameData(HttpServletRequest req, HttpServletResponse resp)
            throws IOException, ServletException, SQLException {
        List<Option> options = new ArrayList();
        List<User> users = userService.getUsers();
        // 将楼层和id填充进Option列表
        for (User user : users) {
            Option op = new Option(user.getNickName(),user.getId());
            options.add(op);
        }

        JSONObject jsObj = new JSONObject();
        jsObj.put("result", "success");
        jsObj.put("options", options);
        return "data:" + jsObj;
    }

    // 处理登录请求
    public String login(HttpServletRequest req, HttpServletResponse resp) {
        //{1}获取用户名 + 密码
        String account = req.getParameter("account");
        String password = req.getParameter("password");
        JSONObject jo = new JSONObject();
        jo.put("result", "failed");
        try {
            User user = userService.doLogin(account, password);
            HttpSession session = req.getSession();
            // 存入用户对象
            session.setAttribute("user", user);
            // 存入菜单钥匙
            session.setAttribute("MENU_KEY", "MENU_" + user.getRoleId());
            jo.put("result", "success");
        } catch (EntityException e) {
            jo.put("cause", e.getMessage());
            e.printStackTrace();
        } catch (SQLException e) {
            jo.put("cause", "服务器内部错误");
            e.printStackTrace();
        }
        return "data:" + jo.toJSONString();
    }

    // 退出登录
    public String signOut(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession();
        // 设置session过期
        session.invalidate();
        // 重定向到登录页
        return "redirect:http://localhost:8080/login.jsp";
    }

    /**
     * 映射地址: /User/jsonList
     * 提交参数: page, limit, ...
     *
     * @return java.lang.String
     */
    public String jsonList(HttpServletRequest req,
                           HttpServletResponse resp)
            throws IOException, ServletException {
        //{1}获取前端提交的关键字 [调BaseController的方法]
        Map<String, Object> keyWords = getKeyWords(req);
        for (String s : keyWords.keySet()) {
            System.out.println("key::" + s + ",value::" + keyWords.get(s));
        }
        String respTxt = "";
        PageBean<User> page = null;
        try {
            //{2}调用 service 方法查询数据(传入关键字)
            page = userService.getUserList(keyWords);
            //{3}转成 json 格式数据.
            respTxt = page.toJSON();
        } catch (Exception e) {
            e.printStackTrace();  //包装错误信息..
            respTxt = packErrMsg(e);
        }
        //{4}返回数据到 LayUI 表格组件。
        return "data:" + respTxt;
    }

    //任务(3)-获取根据 id 获取一个用户
    //映射地址: /User/getUser?id=xxx
    public String getUser(HttpServletRequest req, HttpServletResponse resp)
            throws IOException, ServletException {
        //{1}获取 id 的值
        String id = req.getParameter("id");
        User user = null;
        JSONObject jsObj = new JSONObject();
        String respTxt = "";
        try {
            //{2}根据 id 获取用户
            user = userService.getUserById(id);
            //{3}存入相关信息
            jsObj.put("result", "success");
            jsObj.put("user", user);
            respTxt = jsObj.toString();
        } catch (Exception e) {
            e.printStackTrace();
            respTxt = packErrMsg(e); //打包错误信息
        }
        return "data:" + respTxt;
    }

    //任务(4)-新增 or 更新一个用户。
    //映射地址: /User/saveUser
    public String saveUser(HttpServletRequest req, HttpServletResponse resp)
            throws IOException, ServletException {
        User user = makeUser(req);
        System.out.println("user============" + user);
        JSONObject jsObj = new JSONObject();
        String respTxt = "";
        try {
            userService.saveUser(user);
            jsObj.put("result", "success");
            respTxt = jsObj.toString();
        } catch (SQLException | EntityException e) {
            e.printStackTrace();
            respTxt = packErrMsg(e); //打包错误信息
        }
        return "data:" + respTxt;
    }


    // 将返回的数据封装成对象
    public User makeUser(HttpServletRequest req) {
        User user = new User();
        //{1}修改时使用。
        user.setId(req.getParameter("id"));
        //{2}新增时使用。
        user.setAccount(req.getParameter("account"));
        user.setNickName(req.getParameter("nickName"));
        user.setPassword(req.getParameter("password"));
        user.setRoleId(req.getParameter("roleId"));
        user.setNo(req.getParameter("no"));
        user.setSex(req.getParameter("sex"));
        return user;
    }

    /**
     * 添加用户
     * (1)获取表单数据 map
     * (2)封装user对象
     * (3)调用service
     * (4)ajax根据返回值做出响应
     *
     * @return java.lang.String
     */
    public String addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException {
        Map<String, String[]> map = req.getParameterMap();
        // 使用FastJSon将map转为User对象
        User user = JSON.parseObject(JSON.toJSONString(map), User.class);
//        return "data:" + user.toString();
        return "data:" + userService.addUser(user);
    }

    /**
     * 修改用户
     * (1)获取表单数据 map
     * (2)封装user对象
     * (3)调用service
     * (4)ajax根据返回值做出响应
     * 注意：需要先将修改前的数据填充到表单，用户再修改
     *
     * @return java.lang.String
     */
    public String updateUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException {
        Map<String, String[]> map = req.getParameterMap();
        // 使用FastJSon将map转为User对象
        User user = JSON.parseObject(JSON.toJSONString(map), User.class);
        return "data:" + userService.updateUser(user);
    }

    /**
     * 删除用户
     * (1)获取返回id
     * (2)根据id删除用户
     * (3)ajax根据返回值做出响应
     * 注意：删除的时候要有提示
     *
     * @return java.lang.String
     */
    public String delUser(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException {
        JSONObject jo = new JSONObject();
        String id = req.getParameter("id");
        String respTxt = "";
        try {
            userService.deleteUser(id);
            jo.put("result", "success");
            respTxt = jo.toString();
        } catch (SQLException | EntityException e) {
            e.printStackTrace();
            respTxt = packErrMsg(e); //打包错误信息
        }
        return "data:" + respTxt;
    }

    private String packErrMsg(Exception e) {
        JSONObject jsObj = new JSONObject();
        jsObj.put("code", -1);
        jsObj.put("cause", e.getMessage());
        jsObj.put("result", "failed");
        //{ps}如果还有其它后面再加...
        return jsObj.toString();
    }
}